package com.dlx.common.helper;


import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtHelper {
    //token过期时间
    private static long tokenExpiration = 24*60*60*1000;
    //token签名密钥
    private static String tokenSignKey = "123456";

    //根据参数生产token
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setHeaderParam("type","JWT")
                .setHeaderParam("alg","HS256")
                .setSubject("SMMS-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static String createToken(String userName) {
        String token = Jwts.builder()
                .setHeaderParam("type","JWT")
                .setHeaderParam("alg","HS256")
                .setSubject("SMMS-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("username", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    public static boolean checkToken(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            if(!StringUtils.hasText(token)){
                return false;
            }
            Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //根据token得到用户id
    public static Long getUserId(String token) {
        if(!StringUtils.hasText(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }

    //根据token得到用户名称
    public static String getUserName(String token) {
        if(!StringUtils.hasText(token)) {
            return "";
        }
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("username");
    }

//    public static void main(String[] args) {
//        String token = JwtHelper.createToken(1L, "55");
//        System.out.println(token);
//        System.out.println(JwtHelper.getUserId(token));
//        System.out.println(JwtHelper.getUserName(token));
//    }
}
